package com.dm.wallpaper.library.adapters;

import com.dm.wallpaper.library.ResourceTable;
import com.dm.wallpaper.library.ablility.WallpaperBoardBrowserAbility;
import com.dm.wallpaper.library.ablility.WallpaperBoardPreviewAbility;
import com.dm.wallpaper.library.fraction.ContentCompentUtils;
import com.dm.wallpaper.library.database.DataProvider;
import com.dm.wallpaper.library.helpers.ImageSizeHelp;
import com.dm.wallpaper.library.items.Category;
import com.dm.wallpaper.library.items.Wallpaper;
import com.dm.wallpaper.library.utils.ImageSize;
import com.dm.wallpaper.library.utils.Log;
import com.dm.wallpaper.library.utils.Extras;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.app.Context;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MainProvider extends PageSliderProvider implements Component.ClickedListener {
    Ability mAbility;
    Context mContext;
    HashMap<Integer, Component> componentHashMap = new HashMap<>();


    public MainProvider(Ability ability) {
        mAbility = ability;
        mContext = ability.getContext();
    }


    @Override
    public int getCount() {
        return 3;
    }

    @Override
    public Object createPageInContainer(ComponentContainer componentContainer, int i) {
        Component component;
        switch (i) {
            case 1:
                List<Wallpaper> newWallpapers = DataProvider.getInstance().getWallpapers();
                component = ContentCompentUtils.initWallpaperView(newWallpapers, mContext);
                break;
            case 2:
                component = LayoutScatter.getInstance(mContext).parse(ResourceTable.Layout_collection_categories_layout, null, false);
                initCategoriesList(component);
                break;
            default:
                component = LayoutScatter.getInstance(mContext).parse(ResourceTable.Layout_collection_latest_layout, null, false);
                initLatestList(component);
                break;
        }
        componentContainer.addComponent(component);
        componentHashMap.put(i, component);
        return component;
    }

    @Override
    public void notifyDataChanged() {
        super.notifyDataChanged();
    }

    private void initLatestList(Component component) {
        ListContainer listContainer = (ListContainer) component.findComponentById(ResourceTable.Id_list_container_latest);

        List<Wallpaper> list = new ArrayList<>();
        List<Wallpaper> latestWallpapers = DataProvider.getInstance().getLatestWallpapers();
        list.addAll(latestWallpapers);

        LatestListProvider listProvider = new LatestListProvider(mContext, list);
        listContainer.setItemProvider(listProvider);


        listContainer.setItemClickedListener((listContainer1, component1, i, l) -> {
            Wallpaper item = (Wallpaper) listProvider.getItem(i);
            Intent secondIntent = new Intent();
            // 指定待启动FA的bundleName和abilityName
            Operation operation = new Intent.OperationBuilder()
                    .withDeviceId("")
                    .withBundleName(mAbility.getBundleName())
                    .withAbilityName(WallpaperBoardPreviewAbility.class)
                    .build();
            secondIntent.setParam(Extras.EXTRA_LOCAL_ID, item.getId());
            secondIntent.setOperation(operation);
            mAbility.startAbility(secondIntent);
        });

        for (int i = 0; i < latestWallpapers.size(); i++) {
            Wallpaper wallpaper = latestWallpapers.get(i);
            ImageSize dimensions = wallpaper.getDimensions();
            if (dimensions == null || dimensions.getWidth() == 0 || dimensions.getHeight() == 0) {
                ImageSizeHelp.imageSize(mContext, wallpaper, (length, imageSize) -> {
                    wallpaper.setDimensions(imageSize);
                    wallpaper.setSize(length);
                    DataProvider.getInstance().updateWallpaper(wallpaper.getId(), length, imageSize);
                    listProvider.notifyDataChanged();
                });
            }
        }
    }

    private void initCategoriesList(Component component) {
        ListContainer listContainer = (ListContainer) component.findComponentById(ResourceTable.Id_list_container_categories);
        List<Category> list = new ArrayList<>();
        List<Category> categorys = DataProvider.getInstance().getCategorys();
        list.addAll(categorys);
        CategoriesListAdapter listProvider = new CategoriesListAdapter(mContext, list);
        listContainer.setItemProvider(listProvider);

        listContainer.setItemClickedListener(new ListContainer.ItemClickedListener() {
            @Override
            public void onItemClicked(ListContainer listContainer, Component component, int i, long l) {
                Category category = (Category) listProvider.getItem(i);
                Intent getIntent = new Intent();
                Operation opt = new Intent
                        .OperationBuilder()
                        .withBundleName(mAbility.getBundleName())
                        .withAbilityName(WallpaperBoardBrowserAbility.class)
                        .build();
                getIntent.setOperation(opt);
                Log.i("WallpaperBoardPreviewAbilitySlice.onClick([component]):219      " + category.getName() + "     " + category.getCount());
                getIntent.setParam(Extras.EXTRA_CATEGORY, category.getName());
                getIntent.setParam(Extras.EXTRA_COUNT, category.getCount());
                getIntent.setParam(Extras.EXTRA_FRAGMENT_ID, Extras.ID_CATEGORY_WALLPAPERS);
                mAbility.startAbility(getIntent);
            }
        });

    }


    public void notifyWallpaper() {
        Component component = getPageCompent(1);
        if (component instanceof ComponentContainer) {
            for (int i = 0; i < ((ComponentContainer) component).getChildCount(); i++) {
                Component childCompent = ((ComponentContainer) component).getComponentAt(i);
                if (childCompent instanceof TableLayout) {
                    List<Wallpaper> newWallpapers = DataProvider.getInstance().getWallpapers();
                    ContentCompentUtils.initWallpaperView(newWallpapers, (TableLayout) childCompent, true, null);
                    component.invalidate();
                }
            }
        }
    }


    public Component getPageCompent(int i) {
        return componentHashMap.get(i);
    }

    @Override
    public void destroyPageFromContainer(ComponentContainer componentContainer, int i, Object o) {
        Log.i("MainProvider.destroyPageFromContainer([componentContainer, i, o]):142");
        componentContainer.removeComponent((Component) o);
    }


    @Override
    public boolean isPageMatchToObject(Component component, Object o) {
        Log.i("MainProvider.isPageMatchToObject([component, o]):136   ");
        return component == o;
    }


    @Override
    public void onClick(Component component) {
    }
}
